﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using JSC.Core;
using JSC.Core.Data;
using JSC.Portal.Entities;
using JSC.Portal.Module;
using JSC.Portal.Web.Helper;
using JSC.Portal.Resources;
using System.Collections.Specialized;

namespace JSC.Portal.Web.Controllers
{
    public abstract class ModuleController<TModule> : BaseController
        where TModule : ModuleBase
    {
        public Section Section
        {
            get;
            private set;
        }

        public TModule Module
        {
            get;
            private set;
        }

        protected virtual Dictionary<String, String> ModuleActions
        {
            get
            {
                if (Section == null)
                    throw new NullReferenceException("Section is null, please execute LoadModule before accessing this property");
                return GetDefaultModuleActions();
            }
        }

        public void LoadModule(int sectionId)
        {
            IDao<Section> dao = new CommonDao<Section>();
            Section = dao.GetById(sectionId, false);
            Module = (TModule)ModuleBase.GetModuleFromSection(Section, true);
        }

        public void LoadModuleActions()
        {
            ViewData["ModuleActions"] = new SelectList(ModuleActions, "Value", "Key");
        }

        /// <summary>
        /// Original is null after call UIHelper.RenderModuleControl
        /// </summary>
        public new System.Web.Mvc.UrlHelper Url
        {
            get { return new System.Web.Mvc.UrlHelper(this.ControllerContext.RequestContext); }
        }

        protected virtual Dictionary<String, String> GetDefaultModuleActions()
        {
            Dictionary<String, String> result = new Dictionary<String, String>();
            if (ControllerContext.CurrentUserIsInRole(Roles.SiteAdministrator, Roles.Administrator))
                result.Add(Msg.SectionProperties, Url.Action("EditControl", ControllerNames.SECTIONS_CONTROLLER, new { id = Section.Id }));
            return result;
        }

        public PartialViewResult Index(string viewName, int sectionId)
        {
            LoadModule(sectionId);
            Module.Load();
            LoadModuleActions();
            return PartialView(viewName, Module.Data);
        }
    }
}
